import { v4 as uuidv4 } from 'uuid'

export interface WSMessage {
  type: 'chat' | 'ping' | 'pong' | 'system' | 'message_received' | 'ai_start' | 'ai_chunk' | 'ai_end'
  message?: string
  chunk?: string
  full_message?: string
  final_message?: string
  user_message?: string
  model?: string
  timestamp?: string
  session_id?: string
  error?: boolean
}

export interface WSChatRequest {
  type: 'chat'
  message: string
  model?: string
}

export class WebSocketService {
  private ws: WebSocket | null = null
  private sessionId: string
  private reconnectAttempts = 0
  private maxReconnectAttempts = 5
  private reconnectDelay = 1000
  private pingInterval: NodeJS.Timeout | null = null
  private isConnecting = false
  
  // 事件监听器
  private onMessageCallbacks: ((message: WSMessage) => void)[] = []
  private onConnectCallbacks: (() => void)[] = []
  private onDisconnectCallbacks: (() => void)[] = []
  private onErrorCallbacks: ((error: Event) => void)[] = []

  constructor(sessionId?: string) {
    this.sessionId = sessionId || uuidv4()
  }

  // 连接WebSocket
  connect(): Promise<void> {
    if (this.ws?.readyState === WebSocket.OPEN || this.isConnecting) {
      return Promise.resolve()
    }

    this.isConnecting = true
    
    return new Promise((resolve, reject) => {
      try {
        const wsUrl = `ws://localhost:8004/ws/${this.sessionId}`
        console.log('连接WebSocket:', wsUrl)
        
        this.ws = new WebSocket(wsUrl)
        
        this.ws.onopen = () => {
          console.log('WebSocket连接成功')
          this.isConnecting = false
          this.reconnectAttempts = 0
          this.startHeartbeat()
          this.onConnectCallbacks.forEach(cb => cb())
          resolve()
        }
        
        this.ws.onmessage = (event) => {
          try {
            const message: WSMessage = JSON.parse(event.data)
            console.log('收到WebSocket消息:', message)
            this.onMessageCallbacks.forEach(cb => cb(message))
          } catch (error) {
            console.error('解析WebSocket消息失败:', error)
          }
        }
        
        this.ws.onclose = (event) => {
          console.log('WebSocket连接关闭:', event)
          this.isConnecting = false
          this.stopHeartbeat()
          this.onDisconnectCallbacks.forEach(cb => cb())
          
          // 自动重连
          if (this.reconnectAttempts < this.maxReconnectAttempts) {
            setTimeout(() => {
              this.reconnectAttempts++
              console.log(`尝试重连 (${this.reconnectAttempts}/${this.maxReconnectAttempts})`)
              this.connect()
            }, this.reconnectDelay * this.reconnectAttempts)
          }
        }
        
        this.ws.onerror = (error) => {
          console.error('WebSocket错误:', error)
          this.isConnecting = false
          this.onErrorCallbacks.forEach(cb => cb(error))
          reject(error)
        }
        
      } catch (error) {
        this.isConnecting = false
        reject(error)
      }
    })
  }

  // 发送消息
  sendMessage(message: WSChatRequest): boolean {
    if (this.ws?.readyState === WebSocket.OPEN) {
      try {
        this.ws.send(JSON.stringify(message))
        console.log('发送WebSocket消息:', message)
        return true
      } catch (error) {
        console.error('发送WebSocket消息失败:', error)
        return false
      }
    } else {
      console.error('WebSocket未连接，无法发送消息')
      return false
    }
  }

  // 断开连接
  disconnect() {
    this.stopHeartbeat()
    if (this.ws) {
      this.ws.close()
      this.ws = null
    }
  }

  // 获取连接状态
  getConnectionState(): number | null {
    return this.ws?.readyState || null
  }

  // 是否已连接
  isConnected(): boolean {
    return this.ws?.readyState === WebSocket.OPEN
  }

  // 心跳检测
  private startHeartbeat() {
    this.stopHeartbeat()
    this.pingInterval = setInterval(() => {
      if (this.isConnected()) {
        this.sendMessage({ type: 'ping', message: '' })
      }
    }, 30000) // 每30秒发送一次心跳
  }

  private stopHeartbeat() {
    if (this.pingInterval) {
      clearInterval(this.pingInterval)
      this.pingInterval = null
    }
  }

  // 事件监听器管理
  onMessage(callback: (message: WSMessage) => void) {
    this.onMessageCallbacks.push(callback)
    return () => {
      const index = this.onMessageCallbacks.indexOf(callback)
      if (index > -1) {
        this.onMessageCallbacks.splice(index, 1)
      }
    }
  }

  onConnect(callback: () => void) {
    this.onConnectCallbacks.push(callback)
    return () => {
      const index = this.onConnectCallbacks.indexOf(callback)
      if (index > -1) {
        this.onConnectCallbacks.splice(index, 1)
      }
    }
  }

  onDisconnect(callback: () => void) {
    this.onDisconnectCallbacks.push(callback)
    return () => {
      const index = this.onDisconnectCallbacks.indexOf(callback)
      if (index > -1) {
        this.onDisconnectCallbacks.splice(index, 1)
      }
    }
  }

  onError(callback: (error: Event) => void) {
    this.onErrorCallbacks.push(callback)
    return () => {
      const index = this.onErrorCallbacks.indexOf(callback)
      if (index > -1) {
        this.onErrorCallbacks.splice(index, 1)
      }
    }
  }

  // 获取会话ID
  getSessionId(): string {
    return this.sessionId
  }

  // 更新会话ID
  setSessionId(sessionId: string) {
    if (this.sessionId !== sessionId) {
      this.disconnect()
      this.sessionId = sessionId
    }
  }
}

// 创建全局WebSocket服务实例
export const wsService = new WebSocketService()